package com.example.wm.controller;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import okhttp3.RequestBody;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;

@RestController
@RequestMapping("/OcrImg")
public class OcrImgController {

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient();
    private static final String CLIENT_ID = "S0f55BYGAAwLNyTce3DMxYH4";
    private static final String CLIENT_SECRET = "meSmlg6OUdtO2ayHgn0pXvMU1bb1AvAf";

    // 获取百度AccessToken
    private String getAccessToken() throws IOException {
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"
                + "&client_id=" + CLIENT_ID
                + "&client_secret=" + CLIENT_SECRET;

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            String json = response.body().string();
            JsonObject obj = JsonParser.parseString(json).getAsJsonObject();
            return obj.get("access_token").getAsString();
        }
    }

    @PostMapping("/recognize")
    public String recognizeText(@RequestParam("file") MultipartFile file) throws IOException {
        // 1. 获取 access_token
        String accessToken = getAccessToken();
        // 2. 图片转 base64
        byte[] imageBytes = file.getBytes();
        String imgBase64 = Base64.getEncoder().encodeToString(imageBytes);
        // 3. 调用百度OCR接口
        String ocrUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage_loc?access_token=" + accessToken;
        String param = "image=" + URLEncoder.encode(imgBase64, "UTF-8")
                + "&language_type=CHN_ENG"
                + "&detect_direction=true"
                + "&detect_language=true"
                + "&probability=true";

        RequestBody ocrBody = RequestBody.create(param, MediaType.parse("application/x-www-form-urlencoded"));
        Request ocrRequest = new Request.Builder()
                .url(ocrUrl)
                .post(ocrBody)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();


        try (Response ocrResponse = HTTP_CLIENT.newCall(ocrRequest).execute()) {
            JsonObject jsonObject = JsonParser.parseString(ocrResponse.body().string()).getAsJsonObject();
            JsonArray wordsResult = jsonObject.getAsJsonArray("words_result");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < wordsResult.size(); i++) {
                JsonObject item = wordsResult.get(i).getAsJsonObject();
                sb.append(item.get("words").getAsString());
                if (i != wordsResult.size() - 1) {
                    sb.append(" "); // 你可以改成 "\n" 或其它分隔符
                }
            }
            return sb.toString();
        }

    }
}